/* eslint-disable eqeqeq */
import { AddReply } from '@/components/DragModal/formdoms';
import IconFont from '@/components/IconFont';
import { doFetch, getFetch } from '@/utils/doFetch';
import {
  CloseOutlined,
  EditFilled,
  LoadingOutlined,
  MessageFilled,
  SendOutlined,
} from '@ant-design/icons';
import { useModel, useParams } from '@umijs/max';
import { useRequest } from 'ahooks';
import { Avatar, Drawer, message, Popconfirm, Select, Tooltip } from 'antd';
import dayjs from 'dayjs';
import { useEffect, useRef, useState } from 'react';

function difftime(start, end) {
  const diffInMs = start.diff(end);
  if (diffInMs < 60 * 60 * 1000) {
    // 时间差小于 1 小时，转为分钟
    const diffInMinutes = Math.round(diffInMs / (60 * 1000));
    return diffInMinutes + '分钟前';
  } else {
    // 时间差大于等于 1 小时，继续判断是否超过 24 小时
    const diffInHours = Math.round(diffInMs / (60 * 60 * 1000));
    if (diffInHours >= 24) {
      // 时间差超过 24 小时，转为天
      const diffInDays = Math.round(diffInHours / 24);
      return diffInDays + '天前';
    } else {
      // 时间差在 1 小时到 24 小时之间，直接输出小时数
      return diffInHours + '小时前';
    }
  }
}

const emojiarr = ['👍', '👎', '😆', '😊', '😢', '😭', '😂', '🎉', '❤️', '🚀', '👀'];

function qc(arr) {
  let tempArr = [];
  let obj = {};
  let resultArr = [];

  arr.forEach((v) => {
    if (!tempArr.includes(v)) {
      tempArr.push(v);
    }
  });
  arr.forEach((v) => {
    if (obj[v]) {
      obj[v]++;
    } else {
      obj[v] = 1;
    }
  });
  tempArr.forEach((v) => {
    resultArr.push({
      name: v,
      num: obj[v],
    });
  });

  return resultArr;
}

const ReplyChildCard = ({
  user = {},
  reply,
  bereply_user = {},
  otherusers = [],
  setdoreply,
  id,
  msg_id,
  doreply,
  currentUser,
  drawer,
  run,
  loading,
  info,
  formRef,
  children,
  created_at,
  curitem,
  other,
}) => {
  const [curclickid, setcurclickid] = useState();
  const intoRef = useRef();

  useEffect(() => {
    if (curitem?.msg_id == id) {
      intoRef?.current?.scrollIntoView({
        behavior: 'smooth',
        block: 'start',
        inline: 'start',
      });
    }
  }, [curitem?.msg_id]);

  return (
    <div
      style={{
        overflow: 'hidden',
        display: 'flex',
        transition: 'all 0.2s',
        borderTop: '1px solid #fff',
        padding: '12px 12px 0 12px',
        backgroundColor: 'transparent',
      }}
      ref={intoRef}
    >
      <div style={{ flex: 1 }}>
        <div className="spread" style={{ height: 40, marginBottom: 0 }}>
          <div className="center">
            <Tooltip title={user.user_name}>
              <Avatar size="small" src={user?.head_url || null}>
                {user?.head_url ? null : user?.user_name?.charAt(0)}
              </Avatar>
            </Tooltip>
            <span style={{ color: curitem?.msg_id == id ? '#ff4800' : '#333333', textIndent: 12 }}>
              回复&nbsp;<b>{bereply_user?.user_name}</b>
            </span>

            <div className="center" style={{ gap: 8, paddingLeft: 12 }}>
              {qc(info?.map?.((it) => it?.type) ?? [])?.map((it) => {
                return (
                  <div
                    className="emojis"
                    key={it?.name}
                    onClick={() => {
                      setcurclickid(id);
                      if (loading && curclickid == id) return;
                      run({
                        url: `/webtool/v1/msg/${id}`,
                        params: { emoji: it?.name },
                        method: 'PUT',
                      });
                    }}
                  >
                    <span>{emojiarr[it?.name]}</span>
                    <span>{it?.num}</span>
                  </div>
                );
              })}
            </div>
          </div>
          <div
            className="center"
            style={{
              gap: 6,
              display: drawer?.val == 'edit' ? 'none' : 'flex',
              position: 'relative',
            }}
            id={`container${id}`}
          >
            <div
              className="sorts hoveremoji"
              style={{ position: 'relative', justifyContent: 'flex-end' }}
            >
              <div className="center" style={{ position: 'absolute', right: 30, width: 264 }}>
                {emojiarr?.map((it, i) => {
                  return (
                    <div
                      className="emoji"
                      key={i}
                      onClick={() => {
                        setcurclickid(id);
                        if (loading && curclickid == id) return;
                        run({
                          url: `/webtool/v1/msg/${id}`,
                          params: { emoji: i.toString() },
                          method: 'PUT',
                        });
                      }}
                    >
                      {it}
                    </div>
                  );
                })}
              </div>
              <div className="center" style={{ width: 30, height: 30 }}>
                <IconFont type="icon-xiaolian" style={{ fontSize: 16 }} />
              </div>
            </div>

            <div
              className="sorts"
              onClick={async (e) => {
                e.stopPropagation();
                await setdoreply({
                  ...user,
                  curid: msg_id,
                  curitemid: id,
                  type: 'reply',
                });
                setTimeout(() => {
                  intoRef?.current?.scrollIntoView({
                    behavior: 'smooth',
                    block: 'start',
                    inline: 'start',
                  });
                }, 300);
              }}
            >
              <MessageFilled style={{ color: 'rgb(24, 144, 255)' }} />
            </div>
            {currentUser?.id == user?.id ? (
              <div
                className="sorts"
                onClick={async (e) => {
                  e.stopPropagation();
                  await setdoreply({
                    ...bereply_user,
                    curid: msg_id, // 父级消息id
                    curitemid: id, //本身消息id
                    type: 'edit2',
                    other:
                      other
                        ?.split(',')
                        ?.filter((it) => it !== '')
                        ?.map((it) => parseInt(it)) ?? [],
                  });
                  formRef?.current?.setFieldsValue({ reply });
                  setTimeout(() => {
                    intoRef?.current?.scrollIntoView({
                      behavior: 'smooth',
                      block: 'start',
                      inline: 'start',
                    });
                  }, 300);
                }}
              >
                {loading && curclickid == id ? (
                  <LoadingOutlined />
                ) : (
                  <EditFilled style={{ color: 'green' }} />
                )}
              </div>
            ) : null}

            {currentUser?.id == user?.id ? (
              <Popconfirm
                title={'确认删除'}
                placement="left"
                getPopupContainer={() => document.getElementById(`container${id}`)}
                onConfirm={(e) => {
                  e.stopPropagation();
                  setcurclickid(id);
                  run({ url: `/webtool/v1/msg/${id}`, params: {}, method: 'DELETE' });
                }}
                onCancel={(e) => {
                  e.stopPropagation();
                }}
              >
                <div
                  className="sorts"
                  onClick={(e) => {
                    e.stopPropagation();
                  }}
                >
                  {loading && curclickid == id ? (
                    <LoadingOutlined />
                  ) : (
                    <CloseOutlined style={{ color: '#ff4800' }} />
                  )}
                </div>
              </Popconfirm>
            ) : null}
          </div>
        </div>
        <div
          className="limit"
          style={{
            borderRadius: 8,
            marginBottom: 12,
            paddingBottom: 10,
          }}
        >
          <div dangerouslySetInnerHTML={{ __html: reply }}></div>
          <div className="spread" style={{ color: '#666', fontSize: 12 }}>
            <span>{difftime(dayjs(), dayjs(created_at))}</span>
            <span>
              <b style={{ display: otherusers && otherusers?.length > 0 ? 'inline' : 'none' }}>
                @{' '}
              </b>
              {otherusers?.map?.((it) => (
                <span key={it?.user_name} style={{ padding: '0 4px' }}>
                  {it?.user_name}
                </span>
              ))}
            </span>
          </div>
        </div>
      </div>
    </div>
  );
};

const ReplyCard = ({
  user = {},
  reply,
  bereply_user = {},
  otherusers = [],
  setdoreply,
  id,
  doreply,
  currentUser,
  drawer,
  run,
  loading,
  info,
  formRef,
  children,
  created_at,
  curitem,
  other,
}) => {
  const [curclickid, setcurclickid] = useState();
  const intoRef = useRef();

  useEffect(() => {
    if (curitem?.msg_id == id) {
      intoRef?.current?.scrollIntoView({
        behavior: 'smooth',
        block: 'start',
        inline: 'start',
      });
    }
  }, [curitem?.msg_id]);

  return (
    <div
      style={{
        overflow: 'hidden',
        display: 'flex',
        transition: 'all 0.2s',
        borderTop: '1px solid #f0f0f0',
        padding: '12px 12px 0 12px',
        backgroundColor: doreply?.curid === id ? 'rgba(0, 132, 255, 0.1)' : 'transparent',
      }}
      ref={intoRef}
    >
      <div className="info" style={{ flexShrink: 0 }}>
        <Tooltip title={user.user_name}>
          <Avatar size="large" src={user?.head_url || null}>
            {user?.head_url ? null : user?.user_name?.charAt(0)}
          </Avatar>
        </Tooltip>
      </div>
      <div style={{ flex: 1 }}>
        <div className="spread" style={{ height: 40, marginBottom: 12 }}>
          <div className="center">
            <span style={{ color: curitem?.msg_id == id ? '#ff4800' : '#333333' }}>
              回复&nbsp;<b>{bereply_user?.user_name}</b>
            </span>
            <div className="center" style={{ gap: 8, paddingLeft: 12 }}>
              {qc(info?.map?.((it) => it?.type) ?? [])?.map((it) => {
                return (
                  <div
                    className="emojis"
                    key={it?.name}
                    onClick={() => {
                      setcurclickid(id);
                      if (loading && curclickid == id) return;
                      run({
                        url: `/webtool/v1/msg/${id}`,
                        params: { emoji: it?.name },
                        method: 'PUT',
                      });
                    }}
                  >
                    <span>{emojiarr[it?.name]}</span>
                    <span>{it?.num}</span>
                  </div>
                );
              })}
            </div>
          </div>
          <div
            className="center"
            style={{
              gap: 6,
              display: drawer?.val == 'edit' ? 'none' : 'flex',
              position: 'relative',
            }}
            id={`container${id}`}
          >
            <div
              className="sorts hoveremoji"
              style={{ position: 'relative', justifyContent: 'flex-end' }}
            >
              <div className="center" style={{ position: 'absolute', right: 30, width: 264 }}>
                {emojiarr?.map((it, i) => {
                  return (
                    <div
                      className="emoji"
                      key={i}
                      onClick={() => {
                        setcurclickid(id);
                        if (loading && curclickid == id) return;
                        run({
                          url: `/webtool/v1/msg/${id}`,
                          params: { emoji: i.toString() },
                          method: 'PUT',
                        });
                      }}
                    >
                      {it}
                    </div>
                  );
                })}
              </div>
              <div className="center" style={{ width: 30, height: 30 }}>
                <IconFont type="icon-xiaolian" style={{ fontSize: 16 }} />
              </div>
            </div>

            <div
              className="sorts"
              onClick={async (e) => {
                e.stopPropagation();
                await setdoreply({
                  ...user,
                  curid: id,
                  type: 'reply',
                });
                setTimeout(() => {
                  intoRef?.current?.scrollIntoView({
                    behavior: 'smooth',
                    block: 'start',
                    inline: 'start',
                  });
                }, 300);
              }}
            >
              <MessageFilled style={{ color: 'rgb(24, 144, 255)' }} />
            </div>
            {currentUser?.id == user?.id ? (
              <div
                className="sorts"
                id="container"
                onClick={async (e) => {
                  e.stopPropagation();
                  await setdoreply({
                    ...bereply_user,
                    curid: id,
                    type: 'edit1',
                    other:
                      other
                        ?.split(',')
                        ?.filter((it) => it !== '')
                        ?.map((it) => parseInt(it)) ?? [],
                  });
                  formRef?.current?.setFieldsValue({ reply });
                  setTimeout(() => {
                    intoRef?.current?.scrollIntoView({
                      behavior: 'smooth',
                      block: 'start',
                      inline: 'start',
                    });
                  }, 300);
                }}
              >
                {loading && curclickid == id ? (
                  <LoadingOutlined />
                ) : (
                  <EditFilled style={{ color: 'green' }} />
                )}
              </div>
            ) : null}

            {currentUser?.id == user?.id ? (
              <Popconfirm
                title={'确认删除'}
                placement="left"
                getPopupContainer={() => document.getElementById(`container${id}`)}
                onConfirm={(e) => {
                  e.stopPropagation();
                  setcurclickid(id);
                  run({ url: `/webtool/v1/msg/${id}`, params: {}, method: 'DELETE' });
                }}
                onCancel={(e) => {
                  e.stopPropagation();
                }}
              >
                <div
                  className="sorts"
                  onClick={(e) => {
                    e.stopPropagation();
                  }}
                >
                  {loading && curclickid == id ? (
                    <LoadingOutlined />
                  ) : (
                    <CloseOutlined style={{ color: '#ff4800' }} />
                  )}
                </div>
              </Popconfirm>
            ) : null}
          </div>
        </div>
        <div
          className="limit"
          style={{
            padding: '0 12px 16px 12px',
            border: '1px solid #f0f0f0',
            borderRadius: 8,
            marginBottom: 12,
          }}
        >
          <div dangerouslySetInnerHTML={{ __html: reply }}></div>
          <div className="spread" style={{ color: '#666', fontSize: 12 }}>
            <span>{difftime(dayjs(), dayjs(created_at))}</span>
            <span>
              <b style={{ display: otherusers && otherusers?.length > 0 ? 'inline' : 'none' }}>
                @{' '}
              </b>
              {otherusers?.map?.((it) => (
                <span key={it?.user_name} style={{ padding: '0 4px' }}>
                  {it?.user_name}
                </span>
              ))}
            </span>
          </div>
        </div>
        <div style={{ backgroundColor: 'rgba(0,0,0,0.05)', marginBottom: 20, borderRadius: 8 }}>
          {children?.map((it) => {
            return (
              <ReplyChildCard
                key={it?.id}
                {...it}
                drawer={drawer}
                doreply={doreply}
                run={run}
                loading={loading}
                currentUser={currentUser}
                formRef={formRef}
                curitem={curitem}
                setdoreply={(val) => {
                  setdoreply(val);
                }}
              />
            );
          })}
        </div>
      </div>
    </div>
  );
};

function DrawerReply({ drawer, userList, children, extra }) {
  const { id } = useParams();
  const [doreply, setdoreply] = useState(false);
  const {
    initialState: { currentUser, curitem },
    setInitialState,
  } = useModel('@@initialState');
  const formRef = useRef();

  const [submitdata, setsubmitdata] = useState({
    project_id: parseInt(id),
    item_id: null,
    bereply_userid: drawer?.userInfo?.id,
    reply: null,
    other: [],
  });

  useEffect(() => {
    setsubmitdata((s) => ({
      ...s,
      project_id: parseInt(id),
      bereply_userid: drawer?.userInfo?.id,
      other: drawer?.open ? doreply?.other ?? [] : [],
    }));
  }, [drawer?.userInfo?.id, id, doreply?.other, drawer?.open]);


  const allmsg = useRequest(
    async () => {
      if (!drawer.open) return;
      let res = await getFetch({ url: '/webtool/v1/allmsg', params: { item_id: drawer?.id ?? 0 } });
      return res?.data;
    },
    {
      refreshDeps: [drawer?.id, drawer?.open, curitem],
    },
  );

  const { run, loading } = useRequest(
    (params) => {
      return doFetch(params);
    },
    {
      manual: true,
      debounceWait: 600,
      onSuccess: (res) => {
        allmsg?.refresh();
        if (res?.code === 0) {
          formRef.current.setFieldsValue({ reply: '' });
          setdoreply(false);
        }
      },
    },
  );

  return (
    <Drawer
      {...drawer}
      closable={false}
      maskStyle={{
        backgroundColor: 'transparent',
      }}
      width={'100%'}
      contentWrapperStyle={{ maxWidth: 1280 }}
      placement="right"
      extra={extra(setdoreply)}
      destroyOnClose
    >
      <div
        onClick={() => {
          setdoreply(false);
        }}
      >
        <div style={{ padding: 18 }}>{children}</div>
        {allmsg?.data?.map((it) => {
          return (
            <ReplyCard
              key={it?.id}
              {...it}
              drawer={drawer}
              doreply={doreply}
              run={run}
              loading={loading}
              currentUser={currentUser}
              curitem={curitem}
              formRef={formRef}
              setdoreply={(val) => {
                setdoreply(val);
              }}
            />
          );
        })}
        <div style={{ height: doreply ? 490 : 66 }}></div>
      </div>

      {drawer?.val === 'reply' && (
        <div
          style={{
            position: 'fixed',
            bottom: 0,
            backgroundColor: '#fff',
            padding: '12px',
            borderTop: '1px solid #f0f0f0',
          }}
          onClick={() => {
            if (doreply === false) {
              setdoreply(drawer?.userInfo);
            }
          }}
        >
          <div
            style={{
              height: doreply ? 480 : 40,
              overflow: 'hidden',
              display: 'flex',
              transition: 'all 0.2s',
            }}
          >
            <div className="info">
              <Tooltip title={currentUser.user_name}>
                <Avatar size="large" src={currentUser?.head_url || null}>
                  {currentUser?.head_url ? null : currentUser.user_name?.charAt(0)}
                </Avatar>
              </Tooltip>
            </div>
            <div>
              <div
                className="spread"
                style={{ height: 40, marginBottom: 12, position: 'relative' }}
              >
                <div
                  style={{
                    position: 'absolute',
                    top: 0,
                    left: 0,
                    right: 0,
                    margin: 'auto',
                    width: 54,
                    height: 3,
                    borderRadius: 6,
                    backgroundColor: '#ccc',
                  }}
                ></div>
                <div className="centerl" style={{ flex: 1 }}>
                  <span>
                    回复 <b>{doreply?.user_name ?? '-'}</b>
                  </span>

                  <b style={{ padding: '0 12px', fontSize: 16 }}>@</b>
                  <Select
                    mode="multiple"
                    allowClear
                    value={submitdata?.other}
                    onChange={(val) => {
                      setsubmitdata((s) => ({
                        ...s,
                        other: val,
                      }));
                    }}
                    placeholder="选择提及的人员"
                    options={userList
                      ?.filter((it) => it.id !== currentUser?.id && it?.id !== doreply?.id)
                      ?.map((it) => {
                        return {
                          label: it?.user_name,
                          value: it?.id,
                        };
                      })}
                    style={{ width: '400px' }}
                  ></Select>
                </div>
                <div
                  className="sorts"
                  style={{
                    width: 80,
                    height: 40,
                    backgroundColor: 'rgb(24, 144, 255)',
                    color: '#fff',
                  }}
                  onClick={async (e) => {
                    e.stopPropagation();
                    if (loading || !doreply) {
                      setdoreply(drawer?.userInfo);
                      return;
                    }
                    const reply = formRef.current.getFieldFormatValue('reply');
                    const div = document.createElement('div');
                    div.innerHTML = reply;
                    if (div.innerText === '' || div.innerText.replace(/\s*/g, '') === '') {
                      message.warning('请至少回复一句话！');
                      return;
                    }
                    let extra = {};
                    if (doreply?.curid) {
                      extra = { msg_id: doreply?.curid };
                    }
                    // 设置提及人员
                    const other = submitdata?.other?.toString() ?? '';
                    if (doreply?.type == 'edit2') {
                      run({
                        url: '/webtool/v1/msg/' + doreply?.curitemid,
                        params: {
                          ...submitdata,
                          ...extra,
                          other,
                          item_id: drawer?.id,
                          reply,
                        },
                        method: 'PUT',
                      });
                      return;
                    }
                    if (doreply?.type == 'edit1') {
                      run({
                        url: '/webtool/v1/msg/' + doreply?.curid,
                        params: {
                          ...submitdata,
                          other,
                          item_id: drawer?.id,
                          reply,
                        },
                        method: 'PUT',
                      });
                      return;
                    }

                    run({
                      url: '/webtool/v1/msg',
                      params: {
                        ...submitdata,
                        ...extra,
                        other,
                        item_id: drawer?.id,
                        reply,
                        bereply_userid: doreply?.id,
                      },
                    });
                  }}
                >
                  <b>回复</b>
                  &nbsp;
                  {loading ? (
                    <LoadingOutlined></LoadingOutlined>
                  ) : (
                    <SendOutlined style={{ color: '#fff' }} />
                  )}
                </div>
              </div>
              <div style={{ paddingRight: 4 }}>
                <AddReply formRef={formRef}></AddReply>
              </div>
            </div>
          </div>
        </div>
      )}
    </Drawer>
  );
}

export default DrawerReply;
